<template>
    <div class="materialContent">
        <div class="material-content-list">
            <div v-if="selectMaterials.length && !selectMaterials.some(item => !item)" class="materials">
                <component :is="getCom(selectMaterials)" :materials-info="selectMaterials" @del="del" />
            </div>
        </div>
        <div v-if="!props.isHiddenLabel && selectMaterials.length < maxNum" class="material-content-com">
            <el-popover popper-class="pop_select_box" placement="bottom-start" trigger="hover" :width="popoverWidth">
                <template #reference>
                    <div class="upload_btn">
                        <el-icon><plus /></el-icon>
                        <span class="upload_text">{{ materialLabels }}</span>
                    </div>
                </template>
                <template #default>
                    <div class="upload_pop">
                        <div
                            v-for="tab in materialTabs"
                            :key="tab.type"
                            class="item_pop"
                            @click="openMatericalLib(tab)">
                            <img class="item_pop_icon" :src="tab.icon" alt="" />
                            <span class="item_pop_name">{{ tab.name }}</span>
                        </div>
                    </div>
                </template>
            </el-popover>
        </div>
        <div class="material-content-tips">{{ tips }}</div>
    </div>

    <ZWMatericalLib ref="ZWMatericalLibRef" @submit="getMaterlib" />
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted, inject, shallowRef } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getSuffixIcon, getHashTabs, getImageUrlWH } from '@/utils/utils';
import bus from '@/utils/bus';
import { ElMessage } from 'element-plus';

import ZWMatericalLib from '@/components/channelNew/ZWMatericalLib.vue';
import PhonePicture from './PhonePicture.vue';
import PhoneVideo from './PhoneVideo.vue';
import PhoneAudio from './PhoneAudio.vue';
import PhoneLink from './PhoneLink.vue';
import PhoneAward from './PhoneAward.vue';
import PhoneCollection from './PhoneCollection.vue';
import PhoneGoods from './PhoneGoods.vue';
import PhonePage from './PhonePage.vue';
import PhoneMiniProgram from './PhoneMiniProgram.vue';

const ZWMatericalLibRef = ref<HTMLElement>();

interface Props {
    modelValue: string;
    isHiddenLabel: boolean;
    ecommerceShareDisabled: boolean;
    reKey: string;
    tabs: Array<string>;
    materialData: Array<any>;
}

interface TabsType {
    icon: string;
    [propsName: string]: string | number;
}

interface ConfigType {
    tabs: Array<TabsType>;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    isHiddenLabel: false,
    ecommerceShareDisabled: false,
    reKey: '',
    tabs: () => ['1', '2', '3', '4', '5', '6'],
    materialData: () => []
});

const config = reactive<ConfigType>({
    tabs: [
        {
            type: '1',
            icon: '/static/file/pic.png',
            name: '图片',
            comName: shallowRef(PhonePicture)
        },
        {
            type: '2',
            icon: '/static/file/mov.png',
            name: '视频',
            comName: shallowRef(PhoneVideo)
        },
        {
            type: '3',
            icon: '/static/file/link.png',
            name: '链接',
            comName: shallowRef(PhoneLink)
        },
        {
            type: '4',
            icon: '/static/file/mp3.png',
            name: '音频',
            comName: shallowRef(PhoneAudio)
        },
        {
            type: '6',
            icon: '/static/file/wbgg.png',
            name: '抽奖',
            comName: shallowRef(PhoneAward)
        },
        {
            type: '7',
            icon: '/static/file/shop.png',
            name: '商品素材',
            comName: shallowRef(PhoneGoods)
        },
        {
            type: '8',
            icon: '/static/file/shop.png',
            name: '页面素材',
            comName: shallowRef(PhonePage)
        },
        {
            type: '9',
            icon: '/static/file/form.png',
            name: '收集表',
            comName: shallowRef(PhoneCollection)
        },
        {
            type: '11',
            icon: '/static/file/miniApp.png',
            name: '小程序',
            comName: shallowRef(PhoneMiniProgram)
        }
    ]
});

const hashTabs = ref<Array<any>>([]);
const materialLabels = ref<string>('');
const materialTabs = ref<Array<TabsType>>([]);
const selectMaterials = ref<Array<TabsType>>([]);
const originMaterialIds = ref<Array<number>>([]);
// let maxNum = ref<number>(9)
const tips = ref<string>(
    '因企业微信限制，视频建议不超过1280x720，帧率30FPS，视频码率1.67 Mbps，最长不超过30S，最大不超过10MB；大小不超过10M；图片总像素不超过1555200；图片最多添加9张；视频和照片不可同时选取'
);

const popoverWidth = computed(() => {
    return props.tabs.length * 44 + (props.tabs.length - 1) * 8;
});

const maxNum = computed(() => {
    let num = 9;
    if (selectMaterials.value.length) {
        if (selectMaterials.value[0].type === '1') {
            num = 9;
        } else {
            num = 0;
        }
    }
    return num;
});

const getCom = (item: any) => {
    return config.tabs.find(ite => ite.type === item[0].type)?.comName;
};

const getTabs = (): void => {
    const str = '';
    hashTabs.value = getHashTabs();
    if (props.tabs.length) {
        materialLabels.value = props.tabs.reduce((pre, tabKey, index, arr) => {
            return `${pre}${hashTabs.value[tabKey].name}${index < arr.length - 1 ? '/' : ''}`;
        }, str);
        materialTabs.value = props.tabs.map(tabKey => {
            return hashTabs.value[tabKey];
        });
    } else {
        materialLabels.value = str;
    }
};

const openMatericalLib = (tab: TabsType) => {
    ZWMatericalLibRef.value.showTabs = [tab.id];
    const baseId = hashTabs.value[tab.type].id;
    ZWMatericalLibRef.value.baseId = baseId; //打开对应的基础素材
    let maxNum = 0;
    if (tab.type === '1') {
        const num = selectMaterials.value.reduce((pre, cur) => {
            cur.local && pre++;
            return pre;
        }, 0);
        maxNum = 9;
    } else {
        maxNum = 1;
    }
    ZWMatericalLibRef.value.maxNum = maxNum;
    ZWMatericalLibRef.value.localUploadisShow = ['2', '3', '4', '5', '6'];
    if (tab.type == '15') {
        ZWMatericalLibRef.value.multiple = false;
    }
    ZWMatericalLibRef.value.selectInfoList.splice(0);
    if (selectMaterials.value.length && selectMaterials.value[0].type == tab.type) {
        ZWMatericalLibRef.value.selectInfoList.push(...getSelectInfoList());
    }
    ZWMatericalLibRef.value.ecommerceShareDisabled = true;
    ZWMatericalLibRef.value.materVisible = true;
};

const getSelectInfoList = () => {
    return selectMaterials.value.reduce((pre: any, cur: any): any[] => {
        const { type, id } = cur;
        const deleteItem = null;
        const userId = hashTabs.value[type].id;
        const isCheck = true;
        const flag = pre.some((item: any) => {
            if (item.type === type) {
                item.data.push({ ...cur, isCheck });
                return true;
            } else {
                return false;
            }
        });
        if (!flag) {
            const data = [{ ...cur, isCheck }];
            pre.push({ type, id: userId, deleteItem, data });
        }
        return [...pre];
    }, []);
};

const del = (index: number) => {
    selectMaterials.value.splice(index, 1);
    updateMaterials();
};

const getMaterlib = async (res: any): Promise<void> => {
    const arr: any[] = [];
    if (Array.isArray(res)) {
        await Promise.all(
            res.map(item => {
                return (async () => {
                    return item.data.length && arr.push(...(await formatMaterlis(item)));
                })();
            })
        );
        selectMaterials.value.splice(0);
    } else if (res.local) {
        if (selectMaterials.value.length) {
            if (selectMaterials.value[0].type != 1) {
                selectMaterials.value.splice(0);
            } else {
                if (res.type != 1) {
                    selectMaterials.value.splice(0);
                }
            }
        }
        res.data.length && arr.push(...(await formatMaterlis(res)));
    }
    if (!arr.some(item => !item)) {
        selectMaterials.value.push(...arr);
    }
    updateMaterials();
};

const formatMaterlis = async (item: any): Promise<any[]> => {
    const { type, data, local: local = false } = item;
    if (local) {
        return getLocalMaterlis(data, Number(type));
    } else {
        return await getCommonMaterlis(data, Number(type));
    }
};

const getLocalMaterlis = (data: any, type: number) => {
    const local = true;
    switch (type) {
        case 1:
        case 2:
            return data.map((item: any) => {
                const { code, name, url } = item;
                const icon: string = hashTabs.value[type.toString()].icon;
                return {
                    type: type.toString(),
                    icon,
                    name,
                    imgUrl: url || item.imgUrl,
                    videoUrl: url || item.imgUrl,
                    url: url || item.imgUrl,
                    code,
                    local
                };
            });
        case 3:
            return data.map((item: any) => {
                const { code, title, cover_image_url, link_desc, link_url } = item;
                const icon: string = hashTabs.value[type.toString()].icon;
                return {
                    type: type.toString(),
                    icon,
                    name: title || item.name,
                    content: link_desc,
                    linkUrl: cover_image_url || item.linkUrl,
                    code,
                    local,
                    link_title: title || item.name,
                    link_share_image: cover_image_url || item.linkUrl,
                    link_desc,
                    link_url
                };
            });
        default:
            return [];
    }
};

const getCommonMaterlis = async (data: any, type: number): Promise<any[]> => {
    if (type === 10) {
        return mapOfficialAccountsData(data);
    } else {
        return await mapDefaultData(data, type);
    }
};

const mapOfficialAccountsData = (data: any[]): any[] => {
    const list = [
        { name: '', type: 1, iconUrl: '/static/file/official.png' },
        { name: '', type: 2, iconUrl: '/static/file/text.png' },
        { name: '视频', type: 3, iconUrl: '/static/file/mov.png' },
        { name: '音频', type: 4, iconUrl: '/static/file/mp3.png' },
        { name: '图片', type: 5, iconUrl: '/static/file/pic.png' }
    ];
    if (data[0].articleType) {
        return data;
    } else {
        return data[0].article_detail.slice(0, 8).map((item: any) => {
            const type = '10';
            const { type: articleType, id } = item;
            const name = list.find(el => el.type == articleType)?.name || item.title;
            const iconUrl = list.find(el => el.type == articleType)?.iconUrl || '';
            let icon = '';
            if (articleType === 1) {
                icon = item.cover;
            } else {
                icon = iconUrl;
            }
            return { type, name, icon, id, articleType };
        });
    }
};

const mapDefaultData = async (data: any[], type: number): Promise<any> => {
    const res = await Promise.all(mapPromiseList(data, type));
    return res.filter(item => !!item);
};

const mapPromiseList = (data: any[], type: number): any[] => {
    return data.map((item: any) => {
        let flag = false;
        return (async () => {
            let name: string = item[hashTabs.value[type.toString()].field] || item.name;
            let icon: string = hashTabs.value[type.toString()].icon || item.icon;
            const id: string | number = item.id;
            let imgUrl = '';
            let mpUrl = '';
            let videoUrl = '';
            let linkUrl = '';
            let appid = '';
            let content = '';
            let url = '';
            let imgWH = '';
            switch (type) {
                case 1:
                    imgUrl = item.absolute_url || item.imgUrl;
                    if (item.file_size / 1024 / 1024 > 10) {
                        ElMessage.error('图片大小超过10MB');
                        flag = true;
                        break;
                        // return null
                    }
                    imgWH = await getImageUrlWH(imgUrl);
                    if (imgWH.height * imgWH.width > 1555200) {
                        ElMessage.error('图片总像素超过1555200');
                        flag = true;
                        break;
                        // return null
                    }
                    if (imgWH.height > 10800) {
                        ElMessage.error('图片长边超过10800');
                        flag = true;
                        break;
                        // return null
                    }
                    break;
                case 2:
                    videoUrl = item.thumbnail_url || item.videoUrl;
                    url = item.absolute_url;
                    if (item.file_size / 1024 / 1024 > 10) {
                        ElMessage.error('视频大小超过10MB');
                        flag = true;
                        // return null
                    }
                    break;
                case 3:
                    linkUrl = item.cover_image_url || item.linkUrl;
                    name = item.title;
                    content = item.desc;
                    break;
                case 4:
                    content = item.absolute_url;
                    break;
                case 5:
                    name = item.mediaFileInfo?.name || item.name;
                    icon = getSuffixIcon(item.mediaFileInfo?.absolute_url || item.name) || item.icon;
                    break;
                case 6:
                    content = item.qr_code_link;
                    break;
                case 7:
                    name = item.product_name || '';
                    content = item.description || '';
                    break;
                case 8:
                    name = item.page_name || '';
                    content = item.description || '';
                    break;
                case 9:
                    content = item.qr_code_link;
                    break;
                case 11:
                    mpUrl = item.image_url || item.mpUrl;
                    appid = item.appid;
                    break;
            }
            if (flag) {
                return null;
            } else {
                return {
                    type: type.toString(),
                    icon,
                    name,
                    id,
                    imgUrl,
                    mpUrl,
                    videoUrl,
                    linkUrl,
                    appid,
                    content,
                    url
                };
            }
        })();
    });
};

const updateMaterials = () => {
    if (selectMaterials.value.length && !selectMaterials.value.some(item => !item)) {
        bus.emit('selectFriendMaterials', selectMaterials.value);
    }
};

const init = (val: any[]) => {
    originMaterialIds.value.splice(0);
    originMaterialIds.value.push(...val.map(item => item.id));
    selectMaterials.value.splice(0);
    selectMaterials.value.push(...val);
    updateMaterials();
};

watch(
    () => props.materialData,
    val => {
        init(val);
    }
);

onMounted(() => {
    getTabs();
});
</script>

<style lang="scss" scoped>
.materialContent {
    .material-content-list {
        margin: 10px auto;
        width: 100%;
        min-height: 100px;
        .material-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 12px;
            height: 32px;
            line-height: 1;
            background-color: #eee;
            border-radius: 2px;
            margin-bottom: 6px;
            .content {
                flex: 1;
                display: flex;
                align-items: center;
                img {
                    width: 22px;
                    height: 22px;
                }
                span {
                    flex: 1;
                    width: 0;
                    margin: 0 8px;
                    font-size: 12px;
                    line-height: 1;
                    color: #333;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
            }
            .el-icon {
                font-size: 16px;
                color: #888;
                &:hover {
                    cursor: pointer;
                    color: #bbb;
                }
            }
        }
    }
    .material-content-com {
        .upload_btn {
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 8px;
            max-width: 100%;
            height: 32px;
            line-height: 32px;
            background: #f8f8f8;
            border: 1px solid #d9d9d9;
            padding: 0 12px;
            box-sizing: border-box;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            cursor: pointer;
            color: #969696;
            .el-icon {
                vertical-align: middle;
            }
            .upload_text {
                line-height: 32px;
                margin-left: 8px;
                white-space: nowrap;
            }
        }
    }

    .material-content-tips {
        line-height: 1.4;
        font-size: 12px;
        color: #999;
    }
}

.pop_select_box {
    .upload_pop {
        background: #ffffff;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item_pop {
            width: 44px;
            padding-top: 4px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            border: 1px solid #eee;
            &:hover {
                cursor: pointer;
                border-color: #f9a066;
            }
            .item_pop_icon {
                width: 30px;
                height: 30px;
            }
            .item_pop_name {
                font-size: 12px;
                margin-top: 2px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 300;
                color: #555;
            }
        }
    }
}
</style>
